package com.FQJ.stock.config;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 定义Redis的配置
 */
@Configuration
public class CacheConfig {
    /**
     *  当yml中配置了reids数据源的基本信息，底层会自动构建好RedisConnectionFactory连接工厂
     * @param connectionFactory redis的连接工厂
     *                          通过方法入参形式，将容器中的RedisConnectionFactory注入到方法下
     * @return
     */
    @Bean
    public RedisTemplate redisTemplate(@Autowired RedisConnectionFactory connectionFactory){
        //定义模板
        RedisTemplate<String,Object> redisTemplate=new RedisTemplate<>();
        //设置序列化方式
        StringRedisSerializer keySerializer=new StringRedisSerializer();
        Jackson2JsonRedisSerializer<Object> jsonRedisSerializer=new Jackson2JsonRedisSerializer<Object>(Object.class);
        //替换原有的jdk序列化方式
        redisTemplate.setKeySerializer(keySerializer);
        redisTemplate.setHashKeySerializer(keySerializer);
        redisTemplate.setValueSerializer(jsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jsonRedisSerializer);
        //设置工厂
        redisTemplate.setConnectionFactory(connectionFactory);
        //初始化工厂
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
	/**
	 * 构建缓存bean
	 * @return
	 */
	@Bean
	public Cache<String,Object> caffeineCache(){
		Cache<String,Object> cache = Caffeine
				.newBuilder()
				.maximumSize(200)//设置缓存数量上限
//                .expireAfterAccess(1, TimeUnit.SECONDS)//访问1秒后删除
//                .expireAfterWrite(1,TimeUnit.SECONDS)//写入1秒后删除
				.initialCapacity(100)// 初始的缓存空间大小
				.recordStats()//开启统计
				.build();
		return cache;
	}


}
